//
//  passwordView.m
//  支付密码输入框
//
//  Created by 王晓民 on 2018/1/27.
//  Copyright © 2018年 chenwanli. All rights reserved.
//

#import "passwordView.h"
#import "configuration.h"
// 输入密码的位数
static const int boxCount = 6;
// 输入方格的边长
static const CGFloat boxWH = 40;
@interface passwordView()
@property (strong, nonatomic) NSMutableArray *boxes;
// 占位编辑框(这样就点击密码格以外的部分,可以弹出键盘)
@property (weak, nonatomic) UITextField *contentTextField;

@end

@implementation passwordView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor clearColor];
        [self setUpContentView];
    }
    return self;
}

- (void)setUpContentView
{
    UITextField *contentField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    self.contentTextField = contentField;
    contentField.placeholder = @"请输入支付密码";
    contentField.keyboardType =UIKeyboardTypeNumberPad;
    contentField.hidden = YES;
    [contentField addTarget:self action:@selector(txchange:) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:contentField];
    
    // 密码格之间的间隔
    CGFloat margin = 10;
    for (int i = 0; i < boxCount; i++)
    {
        CGFloat x = ([UIScreen mainScreen].bounds.size.width - boxCount * boxWH - (boxCount - 1)* margin) * 0.5 + (boxWH + margin) * i;

        UITextField *pwdLabel = [[UITextField alloc] initWithFrame:CGRectMake(x-30, (self.frame.size.height - boxWH) * 0.5, boxWH, boxWH)];
        pwdLabel.layer.borderColor = wycMain.CGColor;
        pwdLabel.enabled = NO;
        pwdLabel.keyboardType = UIKeyboardTypeNumberPad;
        pwdLabel.textAlignment = NSTextAlignmentCenter;//居中
        pwdLabel.secureTextEntry = YES;//设置密码模式
        pwdLabel.layer.borderWidth = 1;
        [self addSubview:pwdLabel];
        
        [self.boxes addObject:pwdLabel];
    }
    //进入界面，contentTextField 成为第一响应
    [self.contentTextField becomeFirstResponder];
}
#pragma mark 文本框内容改变
- (void)txchange:(UITextField *)tx
{
    NSString *password = tx.text;
    
    for (int i = 0; i < self.boxes.count; i++)
    {
        UITextField *pwdtx = [self.boxes objectAtIndex:i];
        pwdtx.text = @"";
        if (i < password.length)
        {
            NSString *pwd = [password substringWithRange:NSMakeRange(i, 1)];
            pwdtx.text = pwd;
        }
        
    }
    // 输入密码完毕
    if (password.length == boxCount)
    {
        [tx resignFirstResponder];//隐藏键盘
        if (self.returnPasswordStringBlock != nil) {
            self.returnPasswordStringBlock(password);
        }
        
    }
}
#pragma mark --- 懒加载
- (NSMutableArray *)boxes{
    if (!_boxes) {
        _boxes = [NSMutableArray array];
    }
    return _boxes;
}
@end

